package com.xiguanlezz.cn;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/10/29 14:54
 * @Description：
 */
@Slf4j
public class GrpcTestFutureStubClient {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建通信管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 8888)
                .usePlaintext().build();


        // 获取代理对象
        OrderServiceGrpc.OrderServiceFutureStub orderService = OrderServiceGrpc.newFutureStub(managedChannel);

        // 请求参数构造
        OrderServiceProto.OrderRequest request = OrderServiceProto.OrderRequest
                .newBuilder()
                .setUsername("xiguanlezz")
                .setPrice("1024")
                .build();

        ListenableFuture<OrderServiceProto.OrderResponse> responseListenableFuture = orderService.order(request);

        // 异步监听结果
        Futures.addCallback(responseListenableFuture, new FutureCallback<OrderServiceProto.OrderResponse>() {
            @Override
            public void onSuccess(OrderServiceProto.OrderResponse result) {
                log.info("async result: {}", result);
            }

            @Override
            public void onFailure(Throwable t) {

            }
        }, Executors.newCachedThreadPool());

        // 同步获取结果
        OrderServiceProto.OrderResponse response = responseListenableFuture.get();
        log.info("sync result: {}", response);

    }
}
